package com.taotao.service.ipml;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.commons.net.ftp.FTPClient;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.taotao.common.utils.FtpUtil;
import com.taotao.common.utils.IDUtils;
import com.taotao.service.IPictureService;

/**
 * 图片上传业务层
 * 
 * @author Administrator
 *
 */
@Service
public class PictureServiceImpl implements IPictureService {

	@Value("${FTP_ADDRESS}")
	private String FTP_ADDRESS;
	@Value("${FTP_PORT}")
	private Integer FTP_PORT;
	@Value("${FTP_USERNAME}")
	private String FTP_USERNAME;
	@Value("${FTP_PASSWORD}")
	private String FTP_PASSWORD;
	@Value("${FTP_BASE_PATH}")
	private String FTP_BASE_PATH;
	@Value("${IMAGE_BASE_URL}")
	private String IMAGE_BASE_URL;

	/**
	 * 传输图片
	 */
	@Override
	public Map<String, Object> uploadPicture(MultipartFile uploadFile) {
		// TODO Auto-generated method stub
		Map<String, Object> result = new LinkedHashMap<String, Object>();
		try {
			// 获取原始文件名
			String orderName = uploadFile.getOriginalFilename();
			// 获取新的文件名
			String newName = IDUtils.genImageName();
			newName = newName + orderName.substring(orderName.lastIndexOf("."));
			// 使用时间对上传图片进行分目录存放
			String filePath = new DateTime().toString("/yyyy/MM/dd");
			// 使用FTP协议 向nginx服务器上上传图片
			boolean flag = FtpUtil.uploadFile(FTP_ADDRESS, FTP_PORT,
					FTP_USERNAME, FTP_PASSWORD, FTP_BASE_PATH, filePath,
					newName, uploadFile.getInputStream());
			if (flag) {
				result.put("error", 0);
				result.put("url", IMAGE_BASE_URL + filePath + "/" + newName);
				return result;
			} else {
				result.put("error", 1);
				result.put("message ", "文件上传失败");
				return result;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			result.put("error", 1);
			result.put("message ", "文件上传发生异常");
			return result;
		}
	}
}
